﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using ProjectHT.YKDGVB2012.Core.Datacontract;
using Telerik.Web.UI;

namespace ProjectHT.YKDGVB2012.Core.UserControls
{
    public class uc_CreateNew : System.Web.UI.UserControl
    {
        protected RadButton _raddvSave;
        private IMainList _mainlist;
        protected RadTextBox Radtitle;
        protected RadTextBox txtdescription;
        protected RadEditor txtContent;
        protected RadUpload uploadfile;
        protected RadDatePicker txtthoigianthuchien;
        protected CheckBox btnStatus;
        protected CheckBox checkhethan;

        protected HiddenField fileAttch;
        protected HiddenField filename;
        public uc_CreateNew()
        {
            var mainservice = new MainServices(SPContext.GetContext(HttpContext.Current));
            _mainlist = mainservice;

        }

        protected override void OnInit(EventArgs e)
        {
            _raddvSave.Click += new EventHandler(raddvSave_Click);
            base.OnInit(e);

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            var ids = String.Format("{0}", Context.Request.Params[Helper.Constans.ITEMID]);
            if (!IsPostBack)
            {
                if (!String.IsNullOrEmpty(ids))
                {

                    var item = _mainlist.GetbyId(Convert.ToInt32(ids));

                    Radtitle.Text = item.Title;
                    txtthoigianthuchien.SelectedDate = Convert.ToDateTime(item[Common.MainList.FIELDEXPIREDATE]);
                    txtdescription.Text = String.Format("{0}", item[Common.MainList.FIELDDESCRIPTION]);
                    txtContent.Content = String.Format("{0}", item[Common.MainList.FIELDFULLCONTENT]);
                    btnStatus.Checked = (bool)item[Common.MainList.FIELDSTATUS];
                    checkhethan.Checked = (bool)item[Common.MainList.FIELDEXPIRE];
                    var actt = item.Attachments;
                    if (actt.Count > 0)
                    {
                        for (int i = 0; i < actt.Count; i++)
                        {
                            var filepath = "/lists/" + Common.MainList.MAINLIST + "/Attachments/" + item.ID + "/" +
                                      item.Attachments[i];
                            fileAttch.Value = filepath;
                            filename.Value = item.Attachments[i];
                        }
                    }
                }


            }



        }
        protected void raddvSave_Click(object sender, EventArgs e)
        {
            //get value in form to object
            var edm = String.Format("{0}", Context.Request.Params[Helper.Constans.EDITMOD]);

            if (!string.IsNullOrEmpty(edm))
            {
                switch (edm)
                {
                    case "0":
                        CreateNew();
                        break;
                    case "1":
                        Edit();
                        break;

                }

            }

            Page.ClientScript.RegisterStartupScript(this.GetType(), "pageLoad", "Message.alert(\"Dữ liệu đã được câp nhật\", function () { CloseWindow();}, \"\");",
                                                    true);
        }

        private void CreateNew()
        {
            var spcontext = SPContext.GetContext(Context);
            SPSecurity.RunWithElevatedPrivileges(delegate
                                                     {
                                                         using (var site = new SPSite(spcontext.Site.ID))
                                                         {
                                                             using (var sweb = site.OpenWeb())
                                                             {
                                                                 sweb.AllowUnsafeUpdates = true;
                                                                 var olist = sweb.Lists[Common.MainList.MAINLIST];
                                                                 if (olist != null)
                                                                 {
                                                                     var listitem = olist.Items.Add();
                                                                     listitem[Common.MainList.FIELDTITLE] = Radtitle.Text.Trim();
                                                                     listitem[Common.MainList.FIELDDESCRIPTION] = txtdescription.Text;
                                                                     listitem[Common.MainList.FIELDFULLCONTENT] = txtContent.Content;
                                                                     listitem[Common.MainList.FIELDEXPIREDATE] = txtthoigianthuchien.SelectedDate;
                                                                     listitem[Common.MainList.FIELDEXPIRE] = checkhethan.Checked;
                                                                     listitem[Common.MainList.FIELDSTATUS] = btnStatus.Checked;

                                                                     var files = uploadfile.InvalidFiles;
                                                                     if (files.Count > 0)
                                                                     {
                                                                         foreach (UploadedFile file in files)
                                                                         {
                                                                             var fStream = file.InputStream;
                                                                             var contents = new byte[fStream.Length];
                                                                             fStream.Read(contents, 0, (int)fStream.Length);
                                                                             fStream.Close();
                                                                             listitem.Attachments.Add(file.FileName, contents);
                                                                         }
                                                                     }
                                                                     listitem.Update();
                                                                 }
                                                                 sweb.AllowUnsafeUpdates = false;
                                                             }
                                                         }
                                                     });
        }
        private void Edit()
        {
            var ids = string.Format("{0}", Context.Request.Params[Helper.Constans.ITEMID]);
            if (!String.IsNullOrEmpty(ids))
            {
                var spcontext = SPContext.GetContext(Context);
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    using (var site = new SPSite(spcontext.Site.ID))
                    {
                        using (var sweb = site.OpenWeb())
                        {
                            sweb.AllowUnsafeUpdates = true;
                            var olist = sweb.Lists[Common.MainList.MAINLIST];
                            if (olist != null)
                            {
                                var listitem = olist.GetItemById(Convert.ToInt32(ids));
                                listitem[Common.MainList.FIELDTITLE] = Radtitle.Text.Trim();
                                listitem[Common.MainList.FIELDDESCRIPTION] = txtdescription.Text;
                                listitem[Common.MainList.FIELDFULLCONTENT] = txtContent.Content;
                                listitem[Common.MainList.FIELDEXPIREDATE] = txtthoigianthuchien.SelectedDate;
                                listitem[Common.MainList.FIELDEXPIRE] = checkhethan.Checked;
                                listitem[Common.MainList.FIELDSTATUS] = btnStatus.Checked;

                                var files = uploadfile.InvalidFiles;
                                if (files.Count > 0)
                                {
                                    var attch = listitem.Attachments;
                                    var count = attch.Count;
                                    if (count > 0)
                                    {
                                        for (int i = 0; i < count; i++)
                                        {
                                            listitem.Attachments.Delete(listitem.Attachments[i]);
                                        }
                                    }
                                    foreach (UploadedFile file in files)
                                    {
                                        var fStream = file.InputStream;
                                        var contents = new byte[fStream.Length];
                                        fStream.Read(contents, 0, (int)fStream.Length);
                                        fStream.Close();
                                        listitem.Attachments.Add(file.FileName, contents);
                                    }
                                }
                                listitem.Update();
                            }
                            sweb.AllowUnsafeUpdates = false;
                        }
                    }
                });
            }
        }
    }
}
